<?php
/**
 * Created by PhpStorm.
 * User: 刘红波 <liuhb@cqjcdflzxsws.com>
 * Date: 2018/7/26
 * Time: 16:35
 */

namespace app\api\model;


use think\Model;

class WeDetailLikes extends Model
{
    protected $autoWriteTimestamp = true;

    public static function vote($data)
    {
        $exists = self::where($data)->fetchSql(false)->find();
        if (!empty($exists)) {
            if ($exists->is_delete == 0) {
                return ['code' => 0, 'msg' => '已点过赞了'];
            } else if ($exists->is_delete == 1) {
                $result = $exists->save(['is_delete' => 0]);
                WeTopicDetail::where(['id' => $data['detail_id'], 'is_delete' => 0, 'status' => 1])->setInc('likes', 1);
                return $result;
            }

        }

        $res = self::create($data);
        //点赞数+1
        WeTopicDetail::where(['id' => $data['detail_id'], 'is_delete' => 0, 'status' => 1])->setInc('likes', 1);
        return $res;
    }

    public static function cancelVote($data)
    {
        $res = self::where($data)->find();
        if (empty($res)) {
            return ['code' => 0, 'msg' => '未点赞过该话题'];
        } else {
            //点赞数-1
            $res->save(['is_delete' => 1]);
            WeTopicDetail::where(['id' => $data['detail_id'], 'is_delete' => 0, 'status' => 1])->setInc('likes', -1);
            return $res;
        }

    }
}